<template>

    <NuxtLayout name="manage-layout">
        <template #main>

            <div class="min-h-dvh flex justify-center">

                <div class="card bg-base-100 w-11/12 shadow-xl">
                    <div class="card-body">
                        <h4 class="card-title">视力报告列表</h4>
                        <div class="stats shadow w-56">
                            <div class="stat">
                                <div class="stat-figure text-secondary cursor-pointer" @click="showFormModal(null)" v-if="'超级管理员' === loginUserRef.role || '教师' === loginUserRef.role">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                         stroke-width="1.5"
                                         stroke="currentColor" class="size-6">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                              d="M12 4.5v15m7.5-7.5h-15"/>
                                    </svg>
                                </div>
                                <div class="stat-title">数据量</div>
                                <div class="stat-value">{{ tableData.total }}</div>
                                <div class="stat-desc">共{{tableData.pages}}页数据</div>
                            </div>
                        </div>

                        <div class="flex flex-col gap-2">
                            <div class="flex flex-wrap gap-6">
                                <div class="form-control" v-if="'超级管理员' === loginUserRef.role || '教师' === loginUserRef.role">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">学校</span>
                                    </label>
                                    <module-select 
                                        :undefinedOption="'全部'" 
                                        :uri="'/api/user/list'" 
                                        :text-key="'xuexiao'" 
                                        v-model="searchForm.xuexiao"
                                        :filter="(item) => item.xuexiao && item.xuexiao.trim() !== ''"
                                        :unique-key="'xuexiao'" />
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">学号</span>
                                    </label>
                                    <input type="number" v-model="searchForm.xuehao" placeholder="请输入学号"
                                           class="input input-md input-bordered" pattern="[0-9]*" inputmode="numeric"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">姓名</span>
                                    </label>
                                    <input type="text" v-model="searchForm.name"
                                           placeholder="请输入姓名"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">年份</span>
                                    </label>
                                    <select class="select select-bordered input-md w-full max-w-xs" 
                                            :value="searchForm.year"
                                            @change="updateSearchFormYear($event.target.value)">
                                        <option value="">全部</option>
                                        <option v-for="year in yearOptions" :key="year" :value="year">{{year}}年</option>
                                    </select>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">预警状态</span>
                                    </label>
                                    <select class="select select-bordered input-md w-full max-w-xs" v-model="searchForm.alert">
                                        <option :value="undefined">全部</option>
                                        <option v-for="option in alertOptions" :key="option.value" :value="option.value">
                                            {{option.label}}
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="flex">
                            <button class="btn btn-square btn-outline btn-md btn-info" @click="loadData()"
                                    title="查询">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                     stroke-width="1.5"
                                     stroke="currentColor" class="size-6">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/>
                                </svg>
                            </button>
                        </div>


                        <div class="card bg-base-100 w-full shadow-xl">
                            <div class="card-body">
                                <div class="overflow-x-auto">
                                    <table class="table">
                                        <thead>
                                        <tr>
                                            <th class="cursor-pointer" @click="sortBy('xuehao')">
                                                学号
                                                <span v-if="sortKey === 'xuehao'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th class="cursor-pointer" @click="sortBy('name')">
                                                姓名
                                                <span v-if="sortKey === 'name'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th>学校</th>
                                            <th class="cursor-pointer" @click="sortBy('leftEye')">
                                                左眼视力
                                                <span v-if="sortKey === 'leftEye'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th class="cursor-pointer" @click="sortBy('rightEye')">
                                                右眼视力
                                                <span v-if="sortKey === 'rightEye'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th>结论</th>
                                            <th>建议</th>
                                            <th class="cursor-pointer" @click="sortBy('year')">
                                                年份
                                                <span v-if="sortKey === 'year'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th class="cursor-pointer" @click="sortBy('alert')" style="min-width: 180px;">
                                                预警
                                                <span v-if="sortKey === 'alert'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th class="cursor-pointer" @click="sortBy('ct')">
                                                创建时间
                                                <span v-if="sortKey === 'ct'" class="ml-1">
                                                    {{ sortOrder === 'asc' ? '↑' : '↓' }}
                                                </span>
                                            </th>
                                            <th>更新时间</th>
                                            <th></th>
                                        </tr>
                                        </thead>
                                        <tbody>

                                        <tr v-for="item in sortedTableData" class="hover">
                                            <td>{{item.xuehao}}</td>
                                            <td>{{item.name}}</td>
                                            <td>{{item.xuexiao}}</td>
                                            <td>
                                                <span :class="getVisionClass(item.leftEye)">{{item.leftEye}}</span>
                                            </td>
                                            <td>
                                                <span :class="getVisionClass(item.rightEye)">{{item.rightEye}}</span>
                                            </td>
                                            <td>{{item.conclusion}}</td>
                                            <td>{{item.recommend}}</td>
                                            <td>{{item.year}}</td>
                                            <td>
                                                <div class="badge" :class="getAlertClass(item.alert)">
                                                    {{item.alert}}
                                                </div>
                                            </td>
                                            <td>{{item.ct}}</td>
                                            <td>{{item.ut}}</td>
                                            <td>
                                                <button class="btn btn-xs mx-1 hover:bg-green-400" @click="showDetailsModal(item.id)" title="查看">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"/>
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
                                                    </svg>
                                                </button>
                                                <button class="btn btn-xs mx-1 hover:bg-cyan-400" 
                                                        @click="showFormModal(item.id)"
                                                        :disabled="'学生' === loginUserRef.role || !canModifyReport(item)"
                                                        :title="!canModifyReport(item) ? '只能修改当前年份的报告' : '编辑'">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"/>
                                                    </svg>
                                                </button>
                                                <button class="btn btn-xs mx-1 hover:bg-rose-400" 
                                                        @click="del(item.id)"
                                                        :disabled="'学生' === loginUserRef.role || !canModifyReport(item)"
                                                        :title="!canModifyReport(item) ? '只能删除当前年份的报告' : '删除'">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/>
                                                    </svg>
                                                </button>
                                            </td>
                                        </tr>

                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="card-actions justify-center mt-6">
                            <button @click="toPage(item)"
                                    :class="'join-item btn-xs btn' + (item === searchForm.page ? ' btn-neutral ' : '')"
                                    v-for="item in tableData.pagination">{{ item }}
                            </button>
                        </div>
                    </div>
                </div>


                <!--        详情弹出层-->
                <div>
                    <input type="checkbox" id="detailsModal" ref="detailsModalCheckboxRef" class="modal-toggle"
                           @change="detailsModalCheckboxChanged"/>
                    <div class="modal" role="dialog">
                        <div class="modal-box w-6/12 max-w-5xl modal-box-custom">
                            <div class="modal-action">
                                <label for="detailsModal"
                                       class="absolute right-4 top-4 cursor-pointer">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
                                    </svg>
                                </label>
                            </div>
                            <h3 class="text-lg font-bold">查看详情</h3>
                            <div class="mt-4" v-if="detailsData !== null">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">学号</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.xuehao}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">姓名</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.name}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">学校</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.xuexiao}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">左眼视力</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.leftEye}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">右眼视力</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.rightEye}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">结论</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.conclusion}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">建议</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.recommend}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">年份</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.year}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">预警</span>
                                    </label>
                                    <div class="badge" :class="getAlertClass(detailsData.alert)">
                                        {{detailsData.alert}}
                                    </div>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">创建时间</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.ct}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">更新时间</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.ut}}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!--        编辑弹出层-->
                <dialog-modal ref="formDialogModalRef">
                    <template #main>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">学号</span>
                            </label>
                            <input type="number" v-model="form.xuehao" placeholder="请输入学号"
                                   class="input input-md input-bordered" pattern="[0-9]*" inputmode="numeric"
                                   :class="{'input-error': formErrors.xuehao}"
                                   @input="validateXuehao"/>
                            <label class="label" v-if="formErrors.xuehao">
                                <span class="label-text-alt text-error">{{formErrors.xuehao}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">左眼视力</span>
                            </label>
                            <input type="number" v-model="form.leftEye" placeholder="请输入左眼视力"
                                   class="input input-md input-bordered" step="0.1" min="0" max="10"
                                   :class="{'input-error': formErrors.leftEye}"
                                   @input="validateVision('leftEye')"/>
                            <label class="label" v-if="formErrors.leftEye">
                                <span class="label-text-alt text-error">{{formErrors.leftEye}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">右眼视力</span>
                            </label>
                            <input type="number" v-model="form.rightEye" placeholder="请输入右眼视力"
                                   class="input input-md input-bordered" step="0.1" min="0" max="10"
                                   :class="{'input-error': formErrors.rightEye}"
                                   @input="validateVision('rightEye')"/>
                            <label class="label" v-if="formErrors.rightEye">
                                <span class="label-text-alt text-error">{{formErrors.rightEye}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">结论</span>
                            </label>
                            <textarea class="textarea textarea-bordered h-24 w-9/12 mt-2" v-model="form.conclusion"
                                      placeholder="请输入结论"
                                      :class="{'textarea-error': formErrors.conclusion}"
                                      @input="validateConclusion"/>
                            <label class="label" v-if="formErrors.conclusion">
                                <span class="label-text-alt text-error">{{formErrors.conclusion}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">建议</span>
                            </label>
                            <textarea class="textarea textarea-bordered h-24 w-9/12 mt-2" v-model="form.recommend"
                                      placeholder="请输入建议"
                                      :class="{'textarea-error': formErrors.recommend}"
                                      @input="validateRecommend"/>
                            <label class="label" v-if="formErrors.recommend">
                                <span class="label-text-alt text-error">{{formErrors.recommend}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">年份</span>
                            </label>
                            <select class="select select-bordered input-md w-full max-w-xs" 
                                    :value="form.year"
                                    @change="updateFormYear($event.target.value)"
                                    :disabled="'教师' === loginUserRef.role"
                                    :class="{'select-error': formErrors.year}">
                                <option :value="undefined">请选择年份</option>
                                <option v-for="year in yearOptions" :key="year" :value="year">{{year}}年</option>
                            </select>
                            <label class="label" v-if="formErrors.year">
                                <span class="label-text-alt text-error">{{formErrors.year}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">预警状态</span>
                            </label>
                            <select class="select select-bordered input-md w-full max-w-xs" 
                                    v-model="form.alert"
                                    :class="{'select-error': formErrors.alert}">
                                <option :value="undefined">请选择预警状态</option>
                                <option v-for="option in alertOptions" :key="option.value" :value="option.value">
                                    {{option.label}}
                                </option>
                            </select>
                            <label class="label" v-if="formErrors.alert">
                                <span class="label-text-alt text-error">{{formErrors.alert}}</span>
                            </label>
                        </div>
                    </template>
                    <template #footer>
                        <div>
                            <button class="btn bg-green-400 hover:bg-green-500 text-white" @click="submitForm()">提交</button>
                        </div>
                    </template>
                </dialog-modal>

            </div>
        </template>
    </NuxtLayout>


</template>

<script setup>

import {httpDel, httpGet, httpPost, genFileUrl, postForm} from "~/utils/http/http-helper.js";
import {generatePaginationArray} from "~/utils/pagination/index.js";
import {notificationError, notificationSuccess, notificationWarning} from "~/utils/notification/index.js";
import auth from "~/utils/auth/index.js";

definePageMeta({
    index: 'manage-baogao',
})

const formDialogModalRef = ref()
const detailsModalCheckboxRef = ref()

const searchForm = ref({
    page: 1,
    size: 10,
    year: undefined,
    alert: undefined,
    name: undefined,
    xuehao: undefined,
    xuexiao: undefined
})
const tableData = ref({
    list: [],
    total: 0,
    pages: '',
    pagination: []
})

const form = ref({})
const detailsData = ref(null)
const loginUserRef = ref({})

// Add new refs for sorting and validation
const sortKey = ref('ct')
const sortOrder = ref('desc')
const formErrors = ref({})
const yearOptions = ref([])

// Add alert status options
const alertOptions = [
    { value: '无问题', label: '无问题' },
    { value: '轻度视力问题', label: '轻度视力问题' },
    { value: '中度视力问题', label: '中度视力问题' },
    { value: '严重视力问题', label: '严重视力问题' }
]

// Get current year
const currentYear = new Date().getFullYear()

// Generate year options (only current year for teachers)
function generateYearOptions() {
    if ('教师' === loginUserRef.value.role) {
        yearOptions.value = [currentYear]
    } else {
        yearOptions.value = Array.from({length: 6}, (_, i) => currentYear - i)
    }
}

// Update search form year filter
function updateSearchFormYear(value) {
    searchForm.value.year = value ? parseInt(value) : undefined
}

// Update form year
function updateFormYear(value) {
    form.value.year = value ? parseInt(value) : undefined
}

// Validate if teacher can modify report
function canModifyReport(report) {
    if ('教师' === loginUserRef.value.role) {
        return report.year === currentYear
    }
    return true
}

// Computed property for sorted table data
const sortedTableData = computed(() => {
    if (!tableData.value.list) return []
    return [...tableData.value.list].sort((a, b) => {
        let aVal = a[sortKey.value]
        let bVal = b[sortKey.value]
        
        // Handle special cases
        if (sortKey.value === 'ct' || sortKey.value === 'ut') {
            aVal = new Date(aVal).getTime()
            bVal = new Date(bVal).getTime()
        }
        
        if (sortOrder.value === 'asc') {
            return aVal > bVal ? 1 : -1
        } else {
            return aVal < bVal ? 1 : -1
        }
    })
})

// Sorting function
function sortBy(key) {
    if (sortKey.value === key) {
        sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
    } else {
        sortKey.value = key
        sortOrder.value = 'asc'
    }
}

// Vision class helper
function getVisionClass(vision) {
    if (vision >= 1) return 'text-success'
    if (vision >= 0.5) return 'text-warning'
    return 'text-error'
}

function getAlertClass(alert) {
    if (alert === '无问题') return 'badge-success'
    if (alert === '轻度视力问题' || alert === '中度视力问题') return 'badge-warning'
    if (alert === '严重视力问题') return 'badge-error'
    return 'badge-ghost'
}

// Form validation functions
function validateXuehao() {
    console.log('form.value.xuehao', form.value.xuehao)
    console.log(form.value.xuehao > 9999999)
    if (!form.value.xuehao) {
        formErrors.value.xuehao = '请输入学号'
    } else if (typeof form.value.xuehao !== 'number') {
        formErrors.value.xuehao = '学号必须是数字'
    } else {
        formErrors.value.xuehao = ''
    }
}

function validateVision(field) {
    const value = form.value[field]
    if (value === undefined || value === '') {
        formErrors.value[field] = '请输入视力值'
    } else if (value < 0 || value > 10) {
        formErrors.value.xuehao = '视力值必须在0-10之间'
    } else {
        formErrors.value[field] = ''
    }
}

function validateConclusion() {
    if (!form.value.conclusion) {
        formErrors.value.conclusion = '请输入结论'
    } else if (form.value.conclusion.length > 500) {
        formErrors.value.conclusion = '结论不能超过500字'
    } else {
        formErrors.value.conclusion = ''
    }
}

function validateRecommend() {
    if (!form.value.recommend) {
        formErrors.value.recommend = '请输入建议'
    } else if (form.value.recommend.length > 500) {
        formErrors.value.recommend = '建议不能超过500字'
    } else {
        formErrors.value.recommend = ''
    }
}

function validateYear() {
    if (!form.value.year) {
        formErrors.value.year = '请选择年份'
    } else if ('教师' === loginUserRef.value.role && form.value.year !== currentYear) {
        formErrors.value.year = '教师只能添加当前年份的报告'
    } else {
        formErrors.value.year = ''
    }
}

function validateAlert() {
    if (!form.value.alert) {
        formErrors.value.alert = '请选择预警状态'
    } else if (!alertOptions.some(option => option.value === form.value.alert)) {
        formErrors.value.alert = '请选择有效的预警状态'
    } else {
        formErrors.value.alert = ''
    }
}

/**
 * 加载登录用户
 */
function loadLoginUser(){
    const localUser = auth.getLocalUser()
    if(null !== localUser){
        loginUserRef.value = localUser
    }
}

/**
 * 初始化表单
 */
function initForm() {
    form.value = {}
    detailsData.value = null
    formErrors.value = {}
}

function detailsModalCheckboxChanged(event) {
    const checked = event.target.checked
    if (checked) {
    } else {
    }
}

/**
 * 展示详情弹出层
 * @param id  主键ID null则为新增
 */
function showDetailsModal(id) {
    httpGet('/api/baogao/' + id).then(resp => {
        if (!resp.success) {
            notificationError(resp.msg)
            return
        }
        const data = resp.data
        detailsData.value = data
        detailsModalCheckboxRef.value.checked = true
    })
}

/**
 * 关闭详情弹出层
 */
function closeDetailsModal() {
    detailsModalCheckboxRef.value.checked = false
    initForm()
}

/**
 * 关闭表单弹出框
 */
function closeFormModal() {
    formDialogModalRef.value.closeDialogModal()
    initForm()
}

/**
 * 表单提交
 * 新增或者更新
 */
function submitForm() {
    // Validate all fields
    validateXuehao()
    validateVision('leftEye')
    validateVision('rightEye')
    validateConclusion()
    validateRecommend()
    validateYear()
    validateAlert()
    
    // Check if there are any errors
    if (Object.values(formErrors.value).some(error => error)) {
        notificationError('请修正表单中的错误')
        return
    }
    
    // For teachers, ensure year is current year
    if ('教师' === loginUserRef.value.role) {
        form.value.year = currentYear
    }
    
    // Continue with original submit logic
    if (detailsData.value === null) {
        httpPost('/api/baogao', form.value).then(resp => {
            if (resp.success) {
                notificationSuccess('添加视力报告成功')
                closeFormModal()
                loadData()
            } else {
                notificationError(resp.msg)
            }
        })
    } else {
        httpPost('/api/baogao/' + detailsData.value.id, form.value).then(resp => {
            if (resp.success) {
                notificationSuccess('编辑视力报告成功')
                closeFormModal()
                loadData()
            } else {
                notificationError(resp.msg)
            }
        })
    }
}

if (process.client) {
    generateYearOptions()
    loadLoginUser()
    loadData()
}

/**
 * 加载分页数据
 */
function loadData() {
    httpGet('/api/baogao', searchForm.value).then(resp => {
        console.log(resp)
        if (!resp.success) {
            notificationError(resp.msg)
            return
        }
        const data = resp.data
        // 数据总数
        const total = data.totalElements
        tableData.value.list = data.content
        tableData.value.total = total
        tableData.value.pages = data.pages
        // 当前页码
        const currentPage = searchForm.value.page
        const pageSize = searchForm.value.size
        const pagination = generatePaginationArray(total, pageSize, currentPage); // 生成分页数组
        tableData.value.pagination = pagination
    })
}

/**
 * 跳转到某页
 * @param selectedPage  页码
 */
function toPage(selectedPage) {
    searchForm.value.page = selectedPage
    loadData()
}

/**
 * 展示模态框
 * @param id  主键ID null则为新增
 */
function showFormModal(id) {
    initForm()
    if (null !== id) {
        httpGet('/api/baogao/' + id).then(resp => {
            if (!resp.success) {
                notificationError(resp.msg)
                return
            }
            const data = resp.data
            // Check if teacher can modify this report
            if ('教师' === loginUserRef.value.role && !canModifyReport(data)) {
                notificationError('只能修改当前年份的报告')
                return
            }
            detailsData.value = data
            form.value = data
            formDialogModalRef.value.showDialogModal('修改视力报告')
        })
    } else {
        // For teachers, set current year by default
        if ('教师' === loginUserRef.value.role) {
            form.value.year = currentYear
        }
        formDialogModalRef.value.showDialogModal('添加视力报告')
    }
}

/**
 * 删除
 * @param id  主键ID
 */
function del(id) {
    httpDel('/api/baogao/' + id).then(resp => {
        if (resp.success) {
            notificationSuccess('删除视力报告成功')
            loadData()
        } else {
            notificationError(resp.msg)
        }
    })
}

</script>

<style scoped>

</style>